package com.face.gaoml.netlibrary.data.cookies;


import com.face.gaoml.netlibrary.data.init.SystemConfig;

import java.io.IOException;

import javax.inject.Inject;

import okhttp3.Interceptor;
import okhttp3.Response;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 *
 * 获取cookies 并且保存
 * Created by gaoml on 2016/12/12.
 */

public class GetCookiesInterceptor implements Interceptor {


    @Inject
    SystemConfig config;


    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            final StringBuffer cookieBuffer = new StringBuffer();
            Observable.from(originalResponse.headers("Set-Cookie"))
                    .map(new Func1<String, String>() {
                        @Override
                        public String call(String s) {
                            String[] cookieArray = s.split(";");
                            return cookieArray[0];
                        }
                    })
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String cookie) {
                            cookieBuffer.append(cookie).append(";");
                        }
                    });


//            if (url.equals(Constant.URL_USER + "signin")
//                    || url.equals(Constant.Regist) || url.equals(Constant.OAUTH_SIGNIN_URL)) {
//						MLog.dLog("下来的的cooke:" + rawCookies);
            config.setCooke(cookieBuffer.toString());
//            }


//            SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
//            SharedPreferences.Editor editor = sharedPreferences.edit();
//            editor.putString("cookie", cookieBuffer.toString());
//            editor.commit();
        }
        return originalResponse;
    }
}